/// <reference path="../../index.d.ts" />

var canvas;
var context;
var clockRadius;
var messagePortName = "TizenScreenCaptureMsgPort"; // Remote port name
var remoteAppId = "2lfUowOjEK.TizenCaptureService.dll"; // Target application's App ID


window.onload = function() {
    // Initialize canvas first
    canvas = document.querySelector("canvas");
    context = canvas.getContext("2d");
    document.width = 600;
    clockRadius = document.width / 2;

    //Assigns the area that will use Canvas
    canvas.width = document.width;
    canvas.height = canvas.width;

    // Start the initialization process
    displayResult("Initializing...");
    initializeService();
    

    // add eventListener for keydown
    document.addEventListener('keydown', function(e) {
    	switch(e.keyCode){
    	case 37: //LEFT arrow
    		break;
    	case 38: //UP arrow
    		break;
    	case 39: //RIGHT arrow
    		break;
    	case 40: //DOWN arrow
    		break;
    	case 13: //OK button
    		break;
    	case 10009: //RETURN button
		tizen.application.getCurrentApplication().exit();
    		break;
    	default:
    		console.log('Key code : ' + e.keyCode);
    		break;
    	}
    });

    setInterval(watch, 500);
}

function initializeService() {
    var maxRetries = 5;
    var retryCount = 0;
    var retryInterval = 2000; // 2 seconds

    function tryConnect() {
        try {
            var localPort = tizen.messageport.requestLocalMessagePort(messagePortName, false);
            displayResult("MessagePort created\nTrying to connect to service...");
            
            // Try to establish connection with service
            try {
                var remotePort = tizen.messageport.requestRemoteMessagePort(remoteAppId, messagePortName, false);
                displayResult("Service connection established");
                setupMessagePortAndGetDisplays(localPort);
            } catch (error) {
                if (retryCount === 0) {
                    // First attempt failed, launch the service
                    displayResult("Service not running\nLaunching service...");
                    tizen.application.launch(remoteAppId, function() {
                        displayResult("Service launch initiated");
                        retryCount++;
                        // Wait and retry
                        setTimeout(tryConnect, retryInterval);
                    }, function(error) {
                        displayResult("Failed to launch service:\n" + error.message);
                    });
                } else if (retryCount < maxRetries) {
                    // Service launched but not ready, retry
                    displayResult("Waiting for service... (Attempt " + retryCount + "/" + maxRetries + ")");
                    retryCount++;
                    setTimeout(tryConnect, retryInterval);
                } else {
                    displayResult("Service connection failed after " + maxRetries + " attempts");
                }
            }
        } catch (error) {
            displayResult("Failed to create MessagePort:\n" + error.message);
        }
    }

    tryConnect();
}

function setupMessagePortAndGetDisplays(localPort) {
    // Listen for the response from the remote application
    localPort.addMessagePortListener(function (data, remote) {
        if (data && data.length > 0 && data[0].key === "response") {
            const response = JSON.parse(data[0].value);
            if (response.status === 0 && response.result && response.result.displays) {
                const displayInfo = response.result.displays[0];
                const width = displayInfo.width;
                const height = displayInfo.height;
                console.log("Display Info Received - Width: " + width + ", Height: " + height);
                displayResult("Display Resolution:\n" + width + " x " + height);
            } else {
                displayResult("Failed to get display info");
            }
        }
    });

    try {
        // Construct and send the getDisplays request
        var message = [{ key: "message", value: JSON.stringify({ method: "getDisplays" }) }];
        var remotePort = tizen.messageport.requestRemoteMessagePort(remoteAppId, messagePortName, false);
        remotePort.sendMessage(message, localPort);
        displayResult("Sent display info request");
    } catch (error) {
        displayResult("Failed to send request:\n" + error.message);
    }
}

var displayHistory = []; // Array to store all display messages

function displayResult(result) {
    displayHistory.push(result); // Add new message to history
    updateDisplay(); // Immediately display the result
}

function updateDisplay() {
    // Save current transform
    context.save();
    // Reset any transformations
    context.setTransform(1, 0, 0, 1, 0, 0);
    
    // Clear status area only (right side of canvas)
    context.clearRect(canvas.width/2 + 50, 0, canvas.width/2 - 50, canvas.height);
    
    context.font = "bold 24px Arial"; // Slightly smaller font to fit more text
    context.fillStyle = "#FF0000"; // Red color for better visibility
    
    var lineHeight = 35; // Increased line height
    var startY = 40;
    var currentY = startY;
    
    // Display all messages from history
    displayHistory.forEach(function(message) {
        // Split each message into lines
        var lines = message.split('\n');
        // Draw each line
        lines.forEach(function(line) {
            context.fillText(line, canvas.width/2 + 60, currentY);
            currentY += lineHeight;
        });
        // Add extra spacing between messages
        currentY += 10;
        
        // If we're running out of space, remove oldest messages
        if (currentY > canvas.height - lineHeight) {
            displayHistory.shift(); // Remove oldest message
            // Redraw everything
            context.clearRect(canvas.width/2 + 50, 0, canvas.width/2 - 50, canvas.height);
            currentY = startY;
            displayHistory.forEach(function(msg) {
                var msgLines = msg.split('\n');
                msgLines.forEach(function(ln) {
                    context.fillText(ln, canvas.width/2 + 60, currentY);
                    currentY += lineHeight;
                });
                currentY += 10;
            });
        }
    });
    
    // Restore transform
    context.restore();
}

function watch() {
    // Clear only the clock area (left side of canvas)
    context.clearRect(0, 0, canvas.width/2 + 40, canvas.height);

    //Import the current time
    var date = new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    var hour = hours + minutes / 60;
    var minute = minutes + seconds / 60;

    hours = hours > 12 ? hours - 12 : hours;
    context.save();

    //Assigns the clock creation location in the left side of the canvas
    context.translate(canvas.width/4, canvas.height/2);

    //Assign the style of the number which will be applied to the clock plate
    context.beginPath();
    context.font = "30px monospace";
    context.textAlign = "center";
    context.textBaseline = "middle";
    context.fillStyle = "#555";

    //Create numbers 1 to 12 in a circle
    for (var i = 1; i <= 12; i++) {
        var angle = (i - 3) * (Math.PI * 2) / 12,
            dx = clockRadius * 0.7 * Math.cos(angle),
            dy = clockRadius * 0.7 * Math.sin(angle);
        context.fillText(i, dx, dy);
    }

    //Hour needle
    context.save();
    angle = (hour - 3) * (Math.PI * 2) / 12; //Indicate the current time
    context.rotate(angle);
    context.beginPath();
    context.lineWidth = 4;
    context.lineJoin = "round";
    context.moveTo(-15, -5);
    context.lineTo(-15, 5);
    context.lineTo(clockRadius * 0.4, 0);
    context.closePath();
    context.strokeStyle = "#333";
    context.stroke();
    context.restore(); //Initialize state

    //Minute needle
    context.save();
    angle = (minute - 15) * (Math.PI * 2) / 60;
    context.rotate(angle);
    context.beginPath();
    context.moveTo(-15, -4);
    context.lineTo(-15, 4);
    context.lineTo(clockRadius * 0.7, 1);
    context.lineTo(clockRadius * 0.7, -1);
    context.fill();
    context.restore();

    //Second needle
    context.save();
    angle = (seconds - 15) * (Math.PI * 2) / 60;
    context.rotate(angle);
    context.beginPath();
    context.moveTo(-15, -2);
    context.lineTo(-15, 2);
    context.lineTo(clockRadius * 0.7, 0);
    context.fillStyle = "#f00";
    context.fill();
    context.restore();

    context.restore();
    
    updateDisplay();
}
